package com.example.onlinemusic.controller;

import com.example.onlinemusic.mapper.LoveMusicMapper;
import com.example.onlinemusic.model.Music;
import com.example.onlinemusic.model.User;
import com.example.onlinemusic.tooks.Constant;
import com.example.onlinemusic.tooks.ResponseBodyMessage;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/lovemusic")
public class LoveMusicController {
    @Autowired
    private LoveMusicMapper loveMusicMapper;

    @RequestMapping("/likeMusic")
    public ResponseBodyMessage<Boolean> likeMusic(@RequestParam String id, HttpServletRequest request) {
        HttpSession httpSession = request.getSession(false);
        int musicId = Integer.parseInt(id);
        User user = (User) httpSession.getAttribute(Constant.USERINFO_SESSION_KEY);
        int userId = user.getId();

        Music music = loveMusicMapper.findLoveMusicByMusicIdAndUserId(userId, musicId);
        if (music != null) {
            // 之前收藏过, 不能进行收藏!
            return new ResponseBodyMessage<>(-1, "您之前喜欢过这个音乐", false);
        }
        boolean effect = loveMusicMapper.insertLoveMusic(userId, musicId);
        if (effect) {
            return new ResponseBodyMessage<>(0, "喜欢成功! ", true);
        } else {
            return new ResponseBodyMessage<>(-1, "喜欢失败! ", false);
        }
    }

    @RequestMapping("/findlovemusic")
    public ResponseBodyMessage<List<Music>> findLoveMusic(@RequestParam(required = false) String musicName, HttpServletRequest request) {
        HttpSession httpSession = request.getSession(false);
        User user = (User) httpSession.getAttribute(Constant.USERINFO_SESSION_KEY);
        List<Music> musicList = null;
        if (musicName == null) {
            musicList = loveMusicMapper.findLoveMusicByUserId(user.getId());
        } else {
            musicList = loveMusicMapper.findLoveMusicByKeyAndUID(musicName, user.getId());
        }
        return new ResponseBodyMessage<>(0, "查询到了所有喜欢的音乐!", musicList);
    }

    @RequestMapping("/deletelovemusic")
    public ResponseBodyMessage<Boolean> deleteLoveMusic(@RequestParam String id, HttpServletRequest request) {
        // 1. 查看当前用户是否登录
        HttpSession httpSession = request.getSession(false);
        User user = (User) httpSession.getAttribute(Constant.USERINFO_SESSION_KEY);
        int musicId = Integer.parseInt(id);
        int ret = loveMusicMapper.deleteLoveMusic(user.getId(), musicId);
        if (ret == 1) {
            return new ResponseBodyMessage<>(0, "取消喜欢音乐成功!", true);
        }
        return new ResponseBodyMessage<>(-1, "取消喜欢音乐失败! ", false);
    }
}
